﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using Blazing.Web.Util;
using System.Drawing;
using System.BusinessObjects.Providers;
using System.Web.Caching;
using System.IO;

namespace Blazing.Web.Handlers
{
    public class ThumbnailHandler : IHttpHandler
    {
        #region IHttpHandler Members

        public bool IsReusable
        {
            get { return false; }
        }

        static readonly object ThumbnailhandlerLock = new object();
        public void ProcessRequest(HttpContext context)
        {
            string path = context.Server.MapPath(context.Request.QueryString["File"]);
            if (File.Exists(path))
            {
                int width = int.Parse(context.Request.QueryString["Width"]);
                int height = int.Parse(context.Request.QueryString["Height"]);

                string cacheKey = string.Format("Thumbnail_handler_{0}", CreateHash(string.Format("{0}{1}{2}", path, width, height)));
                byte[] img = CacheProvider.Provider.GetCache<byte[]>(cacheKey);

                if (img == null)
                {
                    lock (ThumbnailhandlerLock)
                    {
                        img = CacheProvider.Provider.GetCache<byte[]>(cacheKey);
                        if (img == null)
                        {
                            ImageResize thumb = new ImageResize()
                            {
                                File = System.Drawing.Image.FromFile(path),
                                Height = height,
                                Width = width,
                                PreserveAspectRatio = true
                            };
                            Image imgtemp = thumb.GetThumbnail();

                            MemoryStream temp = new MemoryStream();
                            imgtemp.Save(temp, System.Drawing.Imaging.ImageFormat.Jpeg);
                            img = temp.ToArray();
                            CacheProvider.Provider.SetCache(cacheKey, img, CacheItemPriority.Low);
                            temp.Dispose();
                        }
                    }
                }

                context.Response.ContentType = "image/Jpeg";
                context.Response.OutputStream.Write(img, 0, img.Length);
                context.Response.Expires = 1440;                
            }
            context.Response.End();
        }

        #endregion

        private string CreateHash(string input)
        {
            byte[] hashBytes = System.Security.Cryptography.MD5.Create().ComputeHash(ASCIIEncoding.ASCII.GetBytes(input));
            return ASCIIEncoding.ASCII.GetString(hashBytes);
        }
    }
}
